<template>
	<view class="father">
		<view class="top">
			<view class="">
				<navigator url="/pages/yonghu1/xichedian/xichedian" open-type="navigateBack">
					<image class="back" src="/static/images/白色左箭头.png" mode=""></image>
				</navigator>
				<view class="title">
					确认订单
				</view>
			</view>
		</view>
		<view class="body">
			<uni-card class="card">
				<view class="liucheng">
					<view class="yyfw">
						<view class="item">
							预约服务
						</view>
					</view>
					<view class="zfdd">
						<view class="item">
							支付订单
						</view>
					</view>
					<view class="mdfw">
						<view class="item">
							门店服务
						</view>
					</view>
				</view>
				<view class="xinxi">
					<image style="width: 20px; height: 20px;margin-top: 10px;" src="../../../static/images/商家@2x.png"
						mode=""></image>
					<view style="margin-left: 10px;">
						<view style="font-size: 14px; font-weight: bold;">
							{{ merchant.name || '加载中...' }}
						</view>
						<view style="font-size: 12px; color: #a9a9a9;">
							{{ merchant.address || '加载中...' }}
						</view>
					</view>
				</view>
				<view class="xinxi">
					<image style="width: 20px; height: 20px;" src="../../../static/images/我的选中.png" mode=""></image>
					<view style="width: 90%; display: flex; justify-content: space-between;  margin-left: 10px;">
						<view style="font-size: 14px; font-weight: bold;">
							{{ user.nickName || user.userName || '加载中...' }}
						</view>
						<view style="font-size: 13px; color: #8E8E8E;">
							{{ user.phone || '加载中...' }}
						</view>
					</view>
				</view>
				<view class="fwcp">
					<view style=" display: flex; justify-content: space-between;">
						<view style="font-size: 14px; font-weight: bold;">
							服务产品
						</view>
						<view style="font-size: 13px; font-weight: bold;">
							共选择<text style="color:#428DFB ;">{{ serviceProducts.length }}项</text>服务产品
						</view>
					</view>
					<view v-for="(item, index) in serviceProducts" :key="index" style="display: flex;margin-top: 10px;">
						<view style=" font-size: 14px; font-weight: bold;">
							{{ item.name }}
						</view>
						<view style="margin-left: 10px; color: red;font-size: 14px; font-weight: bold;">
							￥{{ item.price.toFixed(2) }}
						</view>
					</view>
				</view>
				<view @click="goToCoupons" style="margin-top: 20px;display: flex; margin-bottom: 10px;">
					<image style="margin-top: 2px; height: 20px;width: 20px;" src="../../../static/images/优惠券@2x.png"
						mode=""></image>
					<view style="font-size: 14px; font-weight: bold;margin-left: 10px;">
						{{ selectedCoupon ? (selectedCoupon.type === 0 ? '折扣券' : '代金券') : '代金券/折扣券' }}
					</view>
					<view style="margin-left: 115px; color: red;font-size: 14px; font-weight: bold;">
						{{ selectedCoupon ? (selectedCoupon.type === 0 ? 
							selectedCoupon.name + ' : ' + selectedCoupon.discount + '折' : 
							'满' + selectedCoupon.triggerMoney + '减' + discount.toFixed(2) + '元') : 
							'- ' + discount.toFixed(2) + '元' }}
					</view>
					<image style="margin-top: 2px; margin-left: 10px; width: 20px; height: 20px;"
						src="../../../static/images/右箭头.png" mode=""></image>
				</view>
			</uni-card>
		</view>
		<view class="dibu">
			<view class="left">
				<image style="width: 15px; height: 15px; margin-top: 16px;" src="/static/images/客服@2x.png" mode="">
				</image>
				<view class="kefu" @click="show=true">
					联系客服
				</view>
				<u-popup :show="show" @close="close" @open="open" round="15" mode="bottom">
					<view class="relaDoor">
						<view class="doorItem">18642589456</view>
						<view class="doorItem">复制</view>
						<view class="doorItem" @click="show=false">取消拨号</view>
					</view>
				</u-popup>
			</view>
			<view class="heji">
				合计：￥{{ totalPrice.toFixed(2) }}
			</view>
			<view class="xiadan" @click="submitOrder">
				提交订单
			</view>
		</view>
	</view>
</template>

<script>
	import request from '../../../uitls/request'; // Assuming the request utility is in this path

	export default {
		data() {
			return {
				show: false,
				merchantId: null,
				merchant: {},
				user: {},
				serviceProducts: [], 
				selectedCoupon: null,
				discount: 0, 
				totalPrice: 0 
			}
		},
		onLoad(options) {
			// 在页面显示时设置事件监听，确保每次从优惠券页面返回都能监听到事件
			this.setupEventChannel();
			// 打印从上一个页面接收到的 merchantId
			console.log('从上一页接收到的 merchantId:', options.merchantId);

			// 获取用户信息
			const userInfo = uni.getStorageSync('userInfo');
			this.user = userInfo; // 将获取到的用户信息对象赋值给 this.user
			this.userId = userInfo?.id;

			// 输出用户ID到控制台
			console.log('当前用户ID:', this.userId);
			console.log('完整用户信息:', this.userInfo);
			if (options.merchantId) {
				this.merchantId = options.merchantId;
				this.fetchOrderDetails(this.merchantId);
				this.fetchServiceProducts(this.merchantId); // Example: Fetch service products
			} else {
				uni.showToast({
					title: '未接收到商家信息',
					icon: 'none'
				});

			}
		},
		onShow() {
			
		},
		methods: {
			setupEventChannel() {
				// 获取当前页面的事件通道
				const eventChannel = this.getOpenerEventChannel();
				// 监听来自优惠券页面的 selectedCoupon 事件
				eventChannel.on('selectedCoupon', (data) => {
					console.log('接收到youhuijvan传过来的优惠卷信息:', data.coupon);
					// 如果取消选择优惠券，data.coupon可能为null或undefined
					if (!data.coupon) {
						this.selectedCoupon = null;
						this.discount = 0;
						this.calculateTotalPrice();
						return; // 退出处理
					}
					this.selectedCoupon = data.coupon; // 存储选中的优惠券
					// 根据优惠券类型更新折扣金额
					if (this.selectedCoupon) {
						if (this.selectedCoupon.triggerMoney <= 0) { // 折扣券
							// 假设折扣券直接存储折扣比例 (如 0.8 代表 8折)
							// 您可能需要调整这里的计算逻辑，取决于您的优惠券数据结构
							let servicesTotal = this.serviceProducts.reduce((sum, service) => sum + service.price, 0);
							// 假设 discount 字段存储的是打折数，如 8 代表 8折
							const discountRate = this.selectedCoupon.discount / 10; // 计算实际折扣率 (如 0.8)
							this.discount = servicesTotal * (1 - discountRate); // 计算折扣金额 = 总价 * (1 - 折扣率)
						} else { // 满减券
							this.discount = this.selectedCoupon.preferentialMoney; // 直接使用优惠金额
						}
					} else {
						this.discount = 0; // 如果没有选中优惠券，折扣为0
					}
					this.calculateTotalPrice(); // 重新计算总价
				});
			},
			goToCoupons() {
				uni.navigateTo({
					url: '/pages/yonghu1/youhuijvan/youhuijvan',
					events: {
						selectedCoupon: (data) => {
							console.log('接收到优惠券数据:', data);
							if (data.coupon) {
								this.selectedCoupon = data.coupon;
								// 根据优惠券类型计算折扣
								if (this.selectedCoupon.triggerMoney <= 0) { // 折扣券
									let servicesTotal = this.serviceProducts.reduce((sum, service) => sum + service.price, 0);
									const discountRate = this.selectedCoupon.discount / 10;
									this.discount = servicesTotal * (1 - discountRate);
								} else { // 满减券
									this.discount = this.selectedCoupon.preferentialMoney;
								}
							} else {
								this.selectedCoupon = null;
								this.discount = 0;
							}
							this.calculateTotalPrice();
						}
					}
				});
			},
			xxx(){
				uni.navigateTo({
					url: '/pages/yonghu1/youhuijvan/youhuijvan'
				})
			},
			fetchOrderDetails(merchantId) {
				request({
					url: `/xsc/merchant/${merchantId}`, 
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200 && res.data.data) {
							this.merchant = res.data.data;
							this.calculateTotalPrice();
						} else {
							uni.showToast({
								title: res.data.msg || '获取商家详情失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('请求商家详情失败:', err);
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},
			fetchServiceProducts(merchantId) {
				this.serviceProducts = [{
					name: '精品洗车',
					price: 39.9
				}];
				this.calculateTotalPrice();
			},
			calculateTotalPrice() {
				let servicesTotal = this.serviceProducts.reduce((sum, service) => sum + service.price, 0);
				this.totalPrice = servicesTotal - this.discount;
				if (this.totalPrice < 0) {
					this.totalPrice = 0;
				}
			},
			open() {
			},
			close() {
				this.show = false;
			},
			submitOrder() {
				// 验证服务产品是否存在
				if (!this.serviceProducts || this.serviceProducts.length === 0) {
					uni.showToast({
						title: '请选择服务产品',
						icon: 'none'
					});
					return;
				}

				// 生成随机订单编号 (时间戳 + 6位随机数)
				const timestamp = new Date().getTime();
				const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
				const orderNum = `ORD${timestamp}${randomNum}`;
				
				// 生成UUID作为核销码
				const verificationCode = this.generateUUID();
				
				// 格式化日期为 yyyy-MM-dd HH:mm:ss
				const now = new Date();
				const orderTime = now.getFullYear() + '-' +
					String(now.getMonth() + 1).padStart(2, '0') + '-' +
					String(now.getDate()).padStart(2, '0') + ' ' +
					String(now.getHours()).padStart(2, '0') + ':' +
					String(now.getMinutes()).padStart(2, '0') + ':' +
					String(now.getSeconds()).padStart(2, '0');
				
				// 准备订单数据
				const orderData = {
					merchantId: this.merchantId,
					userId: this.userId,
					orderNum: orderNum,
					orderPrice: this.totalPrice,
					orderStatus: 0, // 待核销状态
					orderTime: orderTime,
					verificationCode: verificationCode,
					couponId: this.selectedCoupon ? this.selectedCoupon.id : null,
					serviceId: this.serviceProducts[0].id || null // 添加空值检查
				};

				console.log('提交订单数据:', orderData);

				// 提交订单
				request({
					url: '/xsc/orders',
					method: 'POST',
					data: orderData,
					success: async (res) => {
						console.log('订单提交响应:', res);
						if (res.data.code === 200) {
							// 如果使用了优惠券，更新优惠券使用数量
							if (this.selectedCoupon) {
								try {
									console.log('开始更新优惠券:', this.selectedCoupon);
									// 更新优惠券使用数量
									const updateRes = await this.updateCouponUsage(this.selectedCoupon.id);
									console.log('优惠券更新结果:', updateRes);
									if (updateRes.code !== 200) {
										throw new Error(updateRes.msg || '更新优惠券失败');
									}
								} catch (error) {
									console.error('更新优惠券使用数量失败:', error);
									uni.showToast({
										title: error.message || '优惠券更新失败',
										icon: 'none',
										duration: 2000
									});
									return; // 添加return防止继续执行
								}
							}
							
							uni.showToast({
								title: '订单提交成功',
								icon: 'success'
							});
							
							// 准备要传递的订单信息
							const orderDetails = {
								orderNum: orderNum,
								merchantName: this.merchant.name || '',
								merchantAddress: this.merchant.address || '',
								servicePrice: this.serviceProducts[0].price || 0,
								originalPrice: this.serviceProducts[0].price || 0,
								merchantDiscount: 0,
								couponDiscount: this.discount || 0,
								orderPrice: this.totalPrice || 0,
								orderTime: orderTime,
								verificationCode: verificationCode,
								merchantId: this.merchantId
							};
							
							console.log('准备传递的订单详情:', orderDetails);
							
							// 将订单详情存储到本地存储
							uni.setStorageSync('currentOrderDetails', orderDetails);
							
							// 跳转到支付成功页面
							uni.redirectTo({
								url: `/pages/yonghu1/tijiaodingdan/tijiaodingdan?orderNum=${orderNum}`
							});
						} else {
							uni.showToast({
								title: res.data.msg || '订单提交失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('订单提交请求失败:', err);
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},
			
			// 生成UUID
			generateUUID() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					const r = Math.random() * 16 | 0;
					const v = c === 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			
			// 更新优惠券使用数量
			async updateCouponUsage(couponId) {
				// 验证必要参数
				if (!this.selectedCoupon || !this.selectedCoupon.id) {
					console.error('优惠券数据不完整:', this.selectedCoupon);
					throw new Error('优惠券数据不完整');
				}

				// 验证优惠券数量
				if (this.selectedCoupon.num <= 0) {
					console.error('优惠券数量不足');
					throw new Error('优惠券数量不足');
				}

				// 构建更新数据，只包含SQL中需要的字段
				const updateData = {
					id: this.selectedCoupon.id,  // 主键ID
					num: this.selectedCoupon.num - 1,  // 更新后的数量
				};

				console.log('更新优惠券参数:', updateData);

				return new Promise((resolve, reject) => {
					request({
						url: '/xsc/usercoupon',
						method: 'PUT',
						header: {
							'Content-Type': 'application/json'
						},
						data: updateData,
						success: (res) => {
							console.log('优惠券更新响应:', res);
							if (res.data.code === 200) {
								resolve(res.data);
							} else {
								console.error('优惠券更新失败，响应数据:', res.data);
								reject(new Error(res.data.msg || '更新优惠券失败'));
							}
						},
						fail: (err) => {
							console.error('优惠券更新请求失败:', err);
							reject(new Error('网络请求失败'));
						}
					});
				});
			}
		},
		watch: {
			// Watch for changes in serviceProducts or discount to recalculate total price
			serviceProducts: {
				handler() {
					this.calculateTotalPrice();
				},
				deep: true
			},
			discount() {
				this.calculateTotalPrice();
			}
		}
	}
</script>

<style scoped>
	.doorItem {
		width: 700rpx;
		height: 80rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		font-weight: bold;

	}

	.father {
		display: flex;
		flex-direction: column;
		/* 垂直排列 */
		height: 100vh;
		/* 父容器高度占满视口 */
	}

	.dibu {
		margin-top: auto;
		background-color: white;
		display: flex;
		height: 50px;
	}

	.dibu .left {
		display: flex;
		margin-left: 20px;
	}

	.dibu .heji {
		line-height: 50px;
		color: red;
		margin-left: 80px;
	}

	.dibu .kefu {
		margin-left: 5px;
		margin-top: 10px;
		height: 30px;
		line-height: 30px;
		font-weight: bold;
		font-size: 12px;
	}

	.dibu .xiadan {
		margin-left: 10px;
		margin-top: 10px;
		height: 30px;
		width: 100px;
		line-height: 30px;
		background-color: #0662E6;
		color: white;
		font-size: 13px;
		text-align: center;
		border-radius: 20px;
	}

	.body {
		border-radius: 10px;
		margin-top: -120px;
	}

	.body .fwcp {
		margin-top: 20px;
	}

	.body .xinxi {
		display: flex;
		margin-top: 20px;

	}

	.body .liucheng {
		margin-top: 10px;
		display: flex;
		justify-content: space-around;
		box-sizing: border-box;
		margin-bottom: 10px;
		border-bottom: 1px solid rgba(247, 247, 247, 1);
		padding-bottom: 20px;
	}

	.body .liucheng .item {
		width: 30px;
		height: 30px;
		margin-left: 13px;
		margin-top: 8px;
		font-size: 12px;
		line-height: 16px;
	}

	.body .liucheng .yyfw {
		width: 50px;
		height: 50px;
		color: white;
		background-image: url('../../../static/images/矩形 4@2x.png');
		background-size: cover;
		background-repeat: no-repeat;
	}

	.body .liucheng .zfdd {
		width: 50px;
		height: 50px;
		color: white;
		background-image: url('../../../static/images/矩形 4 拷贝@2x.png');
		background-size: cover;
		background-repeat: no-repeat;
	}

	.body .liucheng .mdfw {
		width: 50px;
		height: 50px;
		color: white;
		background-image: url('../../../static/images/矩形 4 拷贝 2@2x.png');
		background-size: cover;
		background-repeat: no-repeat;
	}

	.top {
		width: 100%;
		padding-bottom: 120px;
		background: url('../../../static/images/组 8.png');
		background-repeat: no-repeat;
		background-size: cover;
	}

	.top .back {
		position: absolute;
		margin-left: 20px;
		margin-top: 30px;
		width: 15px;
		height: 15px;
		z-index: 2;
	}

	.top .title {
		text-align: center;
		font-size: 18px;
		color: #fff;
		line-height: 44px;
		/* 根据实际需要调整 */
		padding-top: 20px;
	}
</style>